<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="年份" prop="ovyear">
        <el-date-picker v-model="queryParams.ovyear" type="year" value-format="yyyy" placeholder="选择年">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="月份" prop="ovmonth">
        <el-select v-model="queryParams.ovmonth" clearable placeholder="请选择">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单" prop="ordername">
        <el-input v-model="queryParams.ordername" placeholder="请输入订单" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="地区" prop="address">
        <el-input v-model="queryParams.address" placeholder="请输入地区" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="申报人" prop="ovusername">
        <el-input v-model="queryParams.ovusername" placeholder="请输入申报人姓名" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:outputvalue:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:outputvalue:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:outputvalue:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:outputvalue:export']">导出</el-button>
      </el-col>
      <div class="top-right-btn">
        <!-- <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button
            size="mini"
            circle
            icon="el-icon-refresh"
            @click="handleQuery"
          />
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          :content="showSearch ? '隐藏搜索' : '显示搜索'"
          placement="top"
        >
          <el-button
            size="mini"
            circle
            icon="el-icon-search"
            @click="showSearch = !showSearch"
          />
        </el-tooltip> -->
      </div>
    </el-row>

    <el-table v-loading="loading" :data="outputvalueList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="年份" align="center" prop="ovyear" :show-overflow-tooltip="true" />
      <el-table-column label="月份" align="center" prop="ovmonth" :show-overflow-tooltip="true" />
      <el-table-column label="地区" align="center" prop="address" :show-overflow-tooltip="true" />
      <el-table-column label="订单" align="center" width="180" prop="ordername" :show-overflow-tooltip="true" />
      <el-table-column label="含税金额(元)" align="center" width="180" prop="ovmoney" />
      <el-table-column label="不含税金额(元)" align="center" width="180" prop="nonTaxMoney" />
      <el-table-column label="目标完成度" align="center" width="150" prop="targetPercentage" :show-overflow-tooltip="true" />
      <el-table-column label="产值描述" align="center" prop="ovnote" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="申报日期" align="center" prop="ovdate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.ovdate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="申报人id" align="center" prop="ovuserid" :show-overflow-tooltip="true" /> -->
      <el-table-column label="申报人" align="center" prop="ovusername" :show-overflow-tooltip="true" />

      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:outputvalue:edit']">修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:outputvalue:remove']"
            >删除</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改产值对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="年份" prop="ovyear">
          <!-- <el-input v-model="form.ovyear" placeholder="请输入年份" /> -->
          <el-date-picker v-model="form.ovyear" type="year" value-format="yyyy" placeholder="选择年">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="月份" prop="ovmonth" style="width: 283px;">
          <el-select v-model="form.ovmonth" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="系统订单" prop="ordername2" style="width: 283px;">
          <el-input
            v-model="form.ordername2"
            placeholder="请输入系统订单名称"
          />
        </el-form-item> -->
        <el-form-item label="订单" prop="orderid">
          <el-select v-model="form.orderid" placeholder="订单名称" clearable>
            <el-option v-for="dict in orderList" :key="dict.orderid" :label="dict.ordername" :value="dict.orderid" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否含税" prop="isTax">
          <el-select v-model="form.isTax" placeholder="请选择" @change="changeProject">
            <el-option label='是' :value='1'></el-option>
            <el-option label='否' :value='0'></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="isShow" label="税率" prop="rate">
          <el-select v-model="form.rate" placeholder="请选择" @change="changeRate">
            <el-option label="0%" :value="0"></el-option>
            <el-option label="3%" :value="1"></el-option>
            <el-option label="6%" :value="2"></el-option>
            <el-option label="9%" :value="3"></el-option>
            <el-option label="12%" :value="4"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="servin" style="text-align: center;">
          <template>
            <el-table border :header-cell-class-name="starAdd" :data="infiledList" :summary-method="getSummaries"
              style="width: 100%">
              <el-table-column prop="fildna" label="明细">
                <template scope="scope">
                  <el-input size="mini" v-model="scope.row.fildna"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="type" label="产值类型" width="140">
                <template scope="scope">
                  <el-select v-model="scope.row.type" placeholder="请选择">
                    <el-option label='timebase' :value='1'></el-option>
                    <el-option label='taskbase' :value='0'></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="price" label="单价">
                <template scope="scope">
                  <el-input size="mini" v-model="scope.row.price" @change="calculate"
                    onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="counts" label="数量">
                <template scope="scope">
                  <el-input size="mini" v-model="scope.row.counts" @change="calculate"
                    onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="employeeId" label="员工" width="140">
                <template scope="scope">
                  <el-select v-model="scope.row.employeeId" size="mini" clearable>
                    <el-option v-for="item in userList" :key="item.employeeId" :label="item.fullName"
                      :value="item.employeeId">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="correct" label="修正值">
                <template scope="scope">
                  <el-input size="mini" v-model="scope.row.correct" @change="calculate"
                    onkeyup="this.value=this.value.replace(/[^\d.]/g,'');"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="money" label="总金额" width="90">
                <template scope="scope">
                  <el-input size="mini" disabled v-model="scope.row.money"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="remark" label="备注">
                <template scope="scope">
                  <el-input size="mini" v-model="scope.row.remark"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" @click.native.prevent="deleteRow(scope.$index, infiledList)"> 移除 </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
          <el-button type="primary" @click="addRow(infiledList)" style="margin-top: 10px">+增加明细</el-button>
        </el-form-item>
        <el-form-item label="产值总额" prop="ovmoney" style="width: 283px;">
          <el-input v-model="form.ovmoney" placeholder="请输入产值申报金额" disabled maxlength="4" />
        </el-form-item>
        <el-form-item label="不含税额" prop="nonTaxMoney" style="width: 283px;">
          <el-input v-model="form.nonTaxMoney" placeholder="请输入不含税额" disabled maxlength="4" />
        </el-form-item>
        <el-form-item label="产值描述" prop="ovnote" style="width: 283px;">
          <el-input v-model="form.ovnote" type="textarea" placeholder="请输入产值描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="isDisable">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOutputvalue, getOutputvalue, delOutputvalue, addOutputvalue, updateOutputvalue, idAndNameList, userList, exportOutputvalue
} from "@/api/system/outputvalue";

export default {
  name: "Outputvalue",
  components: {},
  props: {},
  data() {
    return {
      //新增
      fromData: {
        list: [],
      },
      list: [
        { name: "明细", type: "", price: "" },
        { name: "明细1", type: "", price: "" },
        { name: "明细2", type: "", price: "" },
      ],
      infiledList: [
        // { fildna: '明细1' ,fildtp: '', counts: "", price: "", money: '',correct: '', remark: ''},
      ],
      type: '',
      price: '',
      counts: '',
      employeeId: '',
      correct: '',
      money: '',
      remark: '',
      columns: [
        {
          title: "明细",
          key: "name",
          width: 200,
        },
        {
          title: "类型",
          key: "type",
          slot: "type",
        },
        {
          title: "单价",
          key: "price",
          slot: "price",
        },
      ],
      isShow: false,
      mounted() {
        this.$set(this.fromData, "list", this.list);
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names: [],
      detailed: 1,
      mesorder: '',
      orderList: [],
      userList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产值表格数据
      outputvalueList: [],
      //valueList: [],
      // 弹出层标题
      title: "",
      //禁止重复提交
      isDisable: false,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ovyear: null,
        ovmonth: null,
        orderid: null,
        ordername: null,
        address: null,
        conId: null,
        value: null,
        conName: null,
        ovmoney: null,
        nonTaxMoney: null,
        rate: null,
        ovtax: null,
        ovdate: null,
        ovuserid: null,
        ovusername: null,
        ovstate: null,
        corpid: null,
        ordercode: null,
        ordername2: null,
        ovnote: null,
        sitename: null,
        helpMoney: null,
        psCode: null,
        pvId: null,
        isTax: '',
        constructionId: null,
        manageFee: null,
        supplierPercent: null,
        detailsList: [],
      },
      //查询月份
      options: [
        {
          value: "1",
          label: "1月",
        },
        {
          value: "2",
          label: "2月",
        },
        {
          value: "3",
          label: "3月",
        },
        {
          value: "4",
          label: "4月",
        },
        {
          value: "5",
          label: "5月",
        },
        {
          value: "6",
          label: "6月",
        },
        {
          value: "7",
          label: "7月",
        },
        {
          value: "8",
          label: "8月",
        },
        {
          value: "9",
          label: "9月",
        },
        {
          value: "`10`",
          label: "10月",
        },
        {
          value: "11",
          label: "11月",
        },
        {
          value: "12",
          label: "12月",
        },
      ],
      value: "",
      // 表单参数
      form: {
        isTax: 1
      },
      // 表单校验
      rules: {
        ovyear: [
          { required: true, message: "年份不能为空", trigger: "change" },
        ],
        // ovmonth: [
        //   { required: true, message: "请选择月份", trigger: "change" }
        // ],
        ovmonth: [
          { required: true, message: "请选择月份", trigger: "change" }
        ],
        orderid: [
          { required: true, message: "订单名称不能为空", trigger: "blur" },
        ],
        isTax: [
          { required: true, message: "含税不能为空", trigger: "blur" },
        ],
        ovmoney: [
          { required: true, message: "请输入产值总额", trigger: "blur" },
          // {
          //   pattern:/^\d+$/,
          //   message:"请填写正确的数字",
          //   trigger:"blur"
          // }
        ],
        nonTaxMoney: [
          { required: true, message: "请输入不含税金额", trigger: "blur" },
          // {
          //   pattern:/^\d+$/,
          //   message:"请填写正确的数字",
          //   trigger:"blur"
          // }
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询产值列表 */
    getList() {
      this.loading = true;
      listOutputvalue(this.queryParams).then((response) => {
        this.outputvalueList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      idAndNameList().then((response) => {
        this.orderList = response.data;
      });
      userList().then((response) => {
        this.userList = response.data;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ovid: null,
        ovyear: null,
        ovmonth: null,
        orderid: null,
        ordername: null,
        conId: null,
        conName: null,
        ovmoney: null,
        nonTaxMoney: null,
        rate: null,
        ovtax: null,
        ovdate: null,
        ovuserid: null,
        ovusername: null,
        ovstate: null,
        corpid: null,
        ordercode: null,
        ordername2: null,
        ovnote: null,
        sitename: null,
        helpMoney: null,
        psCode: null,
        pvId: null,
        isTax: null,
        constructionId: null,
        manageFee: null,
        supplierPercent: null,
        detailsList: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.ovid);
      this.names = selection.map((item) => item.ordername);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.form.detailsList = []
      this.infiledList = [{ fildna: '明细1', fildtp: '', counts: "", price: "", money: '', correct: '', remark: '' },]
      this.reset();
      this.open = true;
      this.title = "添加产值";
      this.form.isTax = 0
      this.isShow = false
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ovid = row.ovid || this.ids;
      getOutputvalue(ovid).then((response) => {
        this.form = response.data;
        this.infiledList = this.form.detailsList
        for (let index = 0; index < this.infiledList.length; index++) {
          this.infiledList[index].fildna = '明细' + (index + 1);
        }
        this.open = true;
        this.title = "修改产值";
      });
    },
    /** 提交按钮 */
    submitForm: function () {
      this.form.detailsList = this.infiledList
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.isDisable = true
          for (let index = 0; index < this.infiledList.length; index++) {
            if (!this.infiledList[index].employeeId) {
              this.$message.error('请选择员工')
            } else {
              // this.isDisable=true
              if (this.form.ovid != undefined) {
                updateOutputvalue(this.form).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess("修改成功");
                    this.isDisable = false
                    this.open = false;
                    this.getList();
                  } else {
                    this.msgError(response.msg);
                    this.isDisable = false
                  }
                });
              } else {
                if (this.form.ovmoney && this.form.nonTaxMoney) {
                  addOutputvalue(this.form).then(response => {
                    if (response.code === 200) {
                      this.msgSuccess("新增成功");
                      this.isDisable = false
                      this.open = false;
                      this.getList();
                    } else {
                      this.msgError(response.msg);
                      this.isDisable = false
                    }
                  });
                } else {
                  this.$message.error('总金额不能为NaN,请填写完整单价、数量、修正值')
                }
              }
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let params = {}
      if (row.bubbles) {
        params = this.names
      } else {
        params = row.ordername
      }
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除产值编号为"' + params + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delOutputvalue(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () { });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有产值数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportOutputvalue(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () { });
    },
    //是否含税
    changeProject(val) {
      if (val == 1) {
        this.isShow = true
        this.form.rate = 0
        this.form.ovmoney = this.mesorder.toFixed(2)
        this.form.nonTaxMoney = (parseFloat(this.mesorder) / (1 + parseFloat(this.form.rate))).toFixed(2);
      } else {
        this.isShow = false
        this.form.rate = 0.06
        this.form.ovmoney = (parseFloat(this.mesorder) * (1 + parseFloat(this.form.rate))).toFixed(2);
        this.form.nonTaxMoney = this.mesorder.toFixed(2)
      }
    },
    // 新增删除一行
    deleteRow(index, rows) {//删除改行
      if (rows.length > 1) {
        rows.splice(index, 1);
        this.form.detailsList = rows
      } else {
        this.$message.error('数据必须1条以上，不能删除！');
      }
    },
    addRow(tableData, event) {
      // tableData.push({ fildna: '',fildtp:'',remark:''
      // })
      this.detailed++
      let obj = {
        'fildna': '明细' + this.detailed,
        'type': '',
        'price': '',
        'counts': '',
        'employeeId': '',
        'correct': '',
        'money': '',
        'remark': '',
      };
      tableData.push(obj);
      this.form.detailsList = tableData
    },
    calculate(row) {
      let sum = 0
      for (let i = 0; i < this.infiledList.length; i++) {
        this.infiledList[i].money = parseFloat(this.infiledList[i].price) * parseFloat(this.infiledList[i].counts) + parseFloat(this.infiledList[i].correct)
        const mstadd = Number(this.infiledList[i].money)
        sum += mstadd
        // this.form.ovmoney = sum
        this.mesorder = sum
        if (this.isShow == true) {
          this.form.ovmoney = this.mesorder.toFixed(2)
          console.log('123444', this.form.ovmoney)
          this.form.nonTaxMoney = (parseFloat(this.mesorder) / (1 + parseFloat(this.form.rate))).toFixed(2);
        } else {
          this.form.rate = 0.06
          this.form.ovmoney = (parseFloat(this.mesorder) * (1 + parseFloat(this.form.rate))).toFixed(2);
          this.form.nonTaxMoney = this.mesorder.toFixed(2)
        }
      }
    },
    // 修改税率
    changeRate(val) {
      if (val == 0) {
        this.form.rate = 0
        this.form.nonTaxMoney = this.mesorder.toFixed(2);
      } else if (val == 1) {
        this.form.nonTaxMoney = (parseFloat(this.mesorder) / 1.03).toFixed(2);
      } else if (val == 2) {
        this.form.nonTaxMoney = (parseFloat(this.mesorder) / 1.06).toFixed(2);
      } else if (val == 3) {
        this.form.nonTaxMoney = (parseFloat(this.mesorder) / 1.09).toFixed(2);
      } else {
        this.form.nonTaxMoney = (parseFloat(this.mesorder) / 1.012).toFixed(2);
      }
    },
    starAdd(obj) {
      if (obj.columnIndex === 0 || obj.columnIndex === 1 || obj.columnIndex === 2 || obj.columnIndex === 3 || obj.columnIndex === 4 || obj.columnIndex === 5) {
        return 'star';
      }
    },
    //指定列求和
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (column.property == 'money') {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index];

        }
      });
      return sums
    },
  },
};
</script>

<style>
table th.star div::after {
  content: "*";
  color: red;
}
</style>

